import {
  getPage
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  $loading,
  $toast,
  promisify,
  storage
} from '../../utils/utils';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
import wxApi from '../../utils/wxApi';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //数据有变化
    pageChange: 0,
    getPage: getPage,
    logged: 0,
    shop: null,
    show: false,
    qrcode: '',
    showRefuse: false,
    closemobile: '',
    dialogConfirm: false,
    navbar: {},
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  onzyClose() {
    this.setData({
      showRefuse: false,
      closemobile: ''
    })
  },
  onmobileChange(e) {
    this.setData({
      closemobile: e.detail
    })
  },
  govip() {
    wxApi.navigateTo(getPage.vip);
  },
  goVipInfo() {
    wxApi.navigateTo(getPage.vipinfo);
  },
  gouserinfo() {
    const {
      real_name,
      birthday,
      region,
      idcardno,
      bank,
      kaihuhang,
      bankno,
    } = this.data;
    wxApi.navigateTo(getPage.userdetail);
    // if (real_name == "待完善")
    //   wxApi.navigateTo(getPage.userdetail);
    // else
    //   $toast(`请联系客服修改`);
  },
  clearweixin(e) {

    promisify(wx.showModal)({
      content: '确认退出登录吗？',
    }).then((res) => {
      if (res.confirm) {
        this.deleteweixin(e);
      }
    });
  },

  /**
   * 删除订单--路由调用
   */
  deleteweixin(e) {
    const {
      userId,
      ShopId
    } = this.data;
    const {
      dataset
    } = e.currentTarget || e.target;

    http.post(api.default, {
      data: {
        action: 'deleteweixin',
        userid: userId
      }
    }).then((res) => {
      console.log(res);
      //成功提示
      $toast(res.data.errmsg, {
        icon: 'success'
      });
      let key = 'shopJbData' + ShopId
      let ns_key = 'shopJbData' + ShopId
      let nullShopJbData = wx.getStorageSync(ns_key)
      let shopJbData = wx.getStorageSync(key)
      wx.clearStorageSync();
      wx.setStorageSync(ns_key, nullShopJbData);
      wx.setStorageSync(key, shopJbData);
      //跳转首页
      // wx.switchTab({
      //   url: getPage.home
      // });
      wxApi.reLaunch(getPage.login);
    });
  },
  /**
   * 替换头像
   */
  modifyAvatar() {
    const that = this;
    let {
      userInfo,
      avatar
    } = this.data;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.showModal({
          content: '确定修改头像？',
          success(res) {
            if (res.confirm) {
              uploadImage({
                filePath: tempFilePaths[0],
                dir: "users",
                success(res) {
                  avatar = res;
                  that.setData({
                    avatar
                  });
                  //更新用户头像
                  that.setUserInfo(() => {
                    $toast('头像保存成功', {
                      icon: 'success'
                    });
                  });
                },
                fail(res) {
                  $toast(`头像上传失败${res}`);
                }
              });
            }
          }
        })
      }
    });
  },

  /**
   * 修改性别
   */
  modifySex() {
    const that = this;
    let {
      userInfo,
      sex
    } = this.data;
    wx.showActionSheet({
      itemList: ['男', '女', '保密'],
      success(res) {
        if (!res.cancel) {
          let str;
          switch (res.tapIndex) {
            case 0:
              str = '男'
              break;
            case 1:
              str = '女'
              break;
            case 2:
              str = '保密'
              break;
          }

          wx.showModal({
            content: '确定修改性别？',
            success(res) {
              if (res.confirm) {
                sex = str;
                that.setData({
                  sex
                });
                //更新用户性别
                that.setUserInfo(() => {
                  $toast('保存成功', {
                    icon: 'success'
                  });
                });
              }
            }
          })
        }
      }
    });
  },
  getqrcode() {
    const {
      userId
    } = this.data;
    http.post(api.default, {
      data: {
        action: 'getqrcode',
        userid: userId
      }
    }).then((res) => {
      this.setData({
        qrcode: res.data.data,
        show: true
      });
      console.log(this.data.qrcode);
    });
  },
  /**
   * 更新用户信息
   */
  setUserInfo(cb) {
    const {
      userId,
      userName,
      nickName,
      avatar,
      sex
    } = this.data;
    http.post(api.default, {
      data: {
        action: 'updateuserinfo',
        userid: userId,
        nickname: nickName,
        sex: sex,
        birthday: '',
        head_img: avatar,
      }
    }).then((res) => {
      cb && cb(res);
      this.setData({
        pageChange: 1
      });
    });
  },
  onBeforeClose: function (action) {
    console.log('action====', action)
    return new Promise((resolve) => {
      if (action === 'confirm') { // 点击确认
        if (!this.data.closemobile) {
          wx.showToast({
            title: '请输入手机号/用户名',
            icon: 'none'
          })
          resolve(false) // 阻止弹框关闭
        } else { // 校验通过
          this.confirmRefuse() // 提交数据，并设置变量是否允许弹框关闭
          resolve(this.data.dialogConfirm)
        }
      } else { // 点击取消
        resolve(true)
        this.setData({
          showRefuse: false
        })
      }
    })
  },
  clearshop() {
    const data = this.data;
    wx.showModal({
      cancelText: '取消',
      confirmText: '确定',
      content: '注销店铺删除店铺所有相关数据',
      success(res) {
        if (res.confirm) {
          let params = {
            action: 'delshop',
            shopid: data.userInfo.data.shop.ShopId,
            userid: data.userId,
          }
          console.log('ppppppparmas===', params)
          http.post(api.default, {
            data: params
          }).then((res) => {
            if (res.data.code == 0) {
              $toast(`删除成功`, {
                icon: 'success'
              });
              const pages = getCurrentPages()[getCurrentPages().length - 2];

              wx.navigateBack({
                delta: 1,
                success() {
                  if (pages !== undefined || pages !== null) {
                    pages.data.pageChange = 1;
                    pages.onLoad();
                  }
                }
              });
            } else {
              $toast(res.data.errmsg, {
                icon: 'fail'
              });
            }
          })
        }
      },
    })
  },
  confirmRefuse(cb) {
    const {
      userId,
      closemobile,
      ShopId
    } = this.data;
    const params = {
      data: {
        action: 'moveshoptouser',
        mobile: closemobile,
        userid: userId,
        shopid: ShopId
      }
    }
    http.post(api.default, {
      data: {
        action: 'moveshoptouser',
        mobile: closemobile,
        userid: userId,
        shopid: ShopId
      }
    }).then((res) => {
      cb && cb(res);
      wxApi.switchTab('/pages/user/user');
    });
    // const res = await http.post(api.default,params)
    // console.log('resssss',res)
    // if (res.code === 0) {
    //   wx.showToast({
    //     title: '操作成功',
    //     icon: 'success'
    //   })
    //   this.setData({showRefuse: false})
    //   this.setData({dialogConfirm: true})
    // } else {
    //   this.setData({dialogConfirm: false})
    //   wx.showToast({
    //     title: res.data.msg,
    //     icon: 'none'
    //   })
    // }
  },
  /**
   * 返回上一页
   */
  goBackTap() {
    console.log('----------', this.data.getPages)
    //存在上一页,关闭当前返回一层,//没有上一页，跳回首页
    this.data.getPages > 1 ? wxApi.navigateBack(1) : wxApi.switchTab(getPage.home);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    //获取路由数量
    this.setData({
      getPages: getCurrentPages().length
    })
    //获取system信息
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
    });
    this.setData({
      beforeClose: (action) => this.onBeforeClose(action)
    })
    //获取登录
    app.getLogin().then((res) => {
      console.log('res.data.user.user_name', res.data.user)
      if (res.data.shop == null)
        res.data.shop = {};
      this.setData({
        userInfo: res,
        logged: res.code,
        isPower: res.data.user.iscanupdateusername,
        userId: res.data.user.user_id,
        ShopId: res.data.shop.ShopId,
        userName: res.data.user.user_name,
        guid: res.data.shop.ShopNo || res.data.user.guid,
        nickName: res.data.user.nickname == "" || res.data.user.nickname == null ? "待完善" : res.data.user.nickname,
        mobile: res.data.user.mobile_phone,
        avatar: res.data.user.head_url,
        birthday: res.data.user.birthday == "1900-01-01 00:00:00" ? "生日有惊喜" : res.data.user.birthday.replace(" 00:00:00", ""),
        sex: res.data.user.sex == "" || res.data.user.sex == 'null' ? "待完善" : res.data.user.sex,

        real_name: res.data.user.real_name == "" || res.data.user.real_name == null ? "待完善" : res.data.user.real_name,
        idcardno: res.data.user.idcardno == "" || res.data.user.idcardno == null ? "待完善" : res.data.user.idcardno,
        bank: res.data.user.bank == "" || res.data.user.bank == null ? "待完善" : res.data.user.bank,
        kaihuhang: res.data.user.kaihuhang == "" || res.data.user.kaihuhang == null ? "待完善" : res.data.user.kaihuhang,
        bankno: res.data.user.bankno == "" || res.data.user.bankno == null ? "待完善" : res.data.user.bankno,
      });
      if (res.data.user.address_id == 0) {
        this.setData({
          address: "待完善"
        });
      } else {
        http.post(api.default, {
          data: {
            action: 'getaddressname',
            id: res.data.user.address_id
          }
        }).then((res) => {
          this.setData({
            address: res.data.data
          });
        });
      }
    }).catch((res) => {
      this.setData({
        logged: res
      });
    });
  },

  zhuanyishop() {
    this.setData({
      showRefuse: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.pageChange) {
      let pages = getCurrentPages()[getCurrentPages().length - 2];
      pages.onLoad();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})